Extracting essential data from a dataset and displaying it is a necessary part of data science; therefore individuals can make correct decisions based on the data. In this assignment, you will extract some stock data, you will then display this data in a graph.
Estimated Time Needed: 30 min
Note:- If you are working in IBM Cloud Watson Studio, please replace the command for installing nbformat from !pip install nbformat==4.2.0 to simply !pip install nbformat
!pip install yfinance==0.1.70
!pip install bs4==4.10.0 -y
!pip install nbformat==4.2.0
!pip install html5lib==1.1
!pip install nbformat==5.9.2
!pip install ipython==8.22.1
Requirement already satisfied: yfinance==0.1.70 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (0.1.70) Requirement already satisfied: pandas>=0.24.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from yfinance==0.1.70) (2.0.3) Requirement already satisfied: numpy>=1.15 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from yfinance==0.1.70) (1.24.3) Requirement already satisfied: requests>=2.26 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from yfinance==0.1.70) (2.31.0) Requirement already satisfied: multitasking>=0.0.7 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from yfinance==0.1.70) (0.0.11) Requirement already satisfied: lxml>=4.5.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from yfinance==0.1.70) (4.9.3) Requirement already satisfied: python-dateutil>=2.8.2 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from pandas>=0.24.0->yfinance==0.1.70) (2.8.2) Requirement already satisfied: pytz>=2020.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from pandas>=0.24.0->yfinance==0.1.70) (2023.3.post1) Requirement already satisfied: tzdata>=2022.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from pandas>=0.24.0->yfinance==0.1.70) (2023.3) Requirement already satisfied: charset-normalizer<4,>=2 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from requests>=2.26->yfinance==0.1.70) (2.0.4) Requirement already satisfied: idna<4,>=2.5 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from requests>=2.26->yfinance==0.1.70) (3.4) Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from requests>=2.26->yfinance==0.1.70) (1.26.16) Requirement already satisfied: certifi>=2017.4.17 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from requests>=2.26->yfinance==0.1.70) (2024.2.2) Requirement already satisfied: six>=1.5 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from python-dateutil>=2.8.2->pandas>=0.24.0->yfinance==0.1.70) (1.16.0) Usage: pip install [options] <requirement specifier> [package-index-options] ... pip install [options] -r <requirements file> [package-index-options] ... pip install [options] [-e] <vcs project url> ... pip install [options] [-e] <local project path> ... pip install [options] <archive url/path> ... no such option: -y Requirement already satisfied: nbformat==4.2.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (4.2.0) Requirement already satisfied: ipython-genutils in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==4.2.0) (0.2.0) Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==4.2.0) (4.17.3) Requirement already satisfied: jupyter-core in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==4.2.0) (5.3.0) Requirement already satisfied: traitlets>=4.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==4.2.0) (5.14.1) Requirement already satisfied: attrs>=17.4.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (22.1.0) Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat==4.2.0) (0.18.0) Requirement already satisfied: platformdirs>=2.5 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from jupyter-core->nbformat==4.2.0) (3.10.0) Requirement already satisfied: html5lib==1.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (1.1) Requirement already satisfied: six>=1.9 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from html5lib==1.1) (1.16.0) Requirement already satisfied: webencodings in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from html5lib==1.1) (0.5.1) Collecting nbformat==5.9.2 Obtaining dependency information for nbformat==5.9.2 from https://files.pythonhosted.org/packages/f4/e7/ef30a90b70eba39e675689b9eaaa92530a71d7435ab8f9cae520814e0caf/nbformat-5.9.2-py3-none-any.whl.metadata Downloading nbformat-5.9.2-py3-none-any.whl.metadata (3.4 kB) Requirement already satisfied: fastjsonschema in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==5.9.2) (2.16.2) Requirement already satisfied: jsonschema>=2.6 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==5.9.2) (4.17.3) Requirement already satisfied: jupyter-core in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==5.9.2) (5.3.0) Requirement already satisfied: traitlets>=5.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from nbformat==5.9.2) (5.14.1) Requirement already satisfied: attrs>=17.4.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from jsonschema>=2.6->nbformat==5.9.2) (22.1.0) Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from jsonschema>=2.6->nbformat==5.9.2) (0.18.0) Requirement already satisfied: platformdirs>=2.5 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from jupyter-core->nbformat==5.9.2) (3.10.0) Downloading nbformat-5.9.2-py3-none-any.whl (77 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 77.6/77.6 kB 1.2 MB/s eta 0:00:00a 0:00:01 Installing collected packages: nbformat Attempting uninstall: nbformat Found existing installation: nbformat 4.2.0 Uninstalling nbformat-4.2.0: Successfully uninstalled nbformat-4.2.0 ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. conda-repo-cli 1.0.75 requires requests_mock, which is not installed. conda-repo-cli 1.0.75 requires clyent==1.2.1, but you have clyent 1.2.2 which is incompatible. conda-repo-cli 1.0.75 requires PyYAML==6.0.1, but you have pyyaml 6.0 which is incompatible. Successfully installed nbformat-5.9.2 Requirement already satisfied: ipython==8.22.1 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (8.22.1) Requirement already satisfied: decorator in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (5.1.1) Requirement already satisfied: jedi>=0.16 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (0.18.1) Requirement already satisfied: matplotlib-inline in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (0.1.6) Requirement already satisfied: prompt-toolkit<3.1.0,>=3.0.41 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (3.0.43) Requirement already satisfied: pygments>=2.4.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (2.15.1) Requirement already satisfied: stack-data in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (0.2.0) Requirement already satisfied: traitlets>=5.13.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (5.14.1) Requirement already satisfied: pexpect>4.3 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from ipython==8.22.1) (4.8.0) Requirement already satisfied: parso<0.9.0,>=0.8.0 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from jedi>=0.16->ipython==8.22.1) (0.8.3) Requirement already satisfied: ptyprocess>=0.5 in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from pexpect>4.3->ipython==8.22.1) (0.7.0) Requirement already satisfied: wcwidth in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from prompt-toolkit<3.1.0,>=3.0.41->ipython==8.22.1) (0.2.5) Requirement already satisfied: executing in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from stack-data->ipython==8.22.1) (0.8.3) Requirement already satisfied: asttokens in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from stack-data->ipython==8.22.1) (2.0.5) Requirement already satisfied: pure-eval in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from stack-data->ipython==8.22.1) (0.2.2) Requirement already satisfied: six in /Users/christian.martin/anaconda3/lib/python3.11/site-packages (from asttokens->stack-data->ipython==8.22.1) (1.16.0)
import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import plotly.graph_objects as go
from plotly.subplots import make_subplots
In Python, you can ignore warnings using the warnings module. You can use the filterwarnings function to filter or ignore specific warning messages or categories.
import warnings
# Ignore all warnings
warnings.filterwarnings("ignore", category=FutureWarning)
In this section, we define the function make_graph. You don't have to know how the function works, you should only care about the inputs. It takes a dataframe with stock data (dataframe must contain Date and Close columns), a dataframe with revenue data (dataframe must contain Date and Revenue columns), and the name of the stock.
def make_graph(stock_data, revenue_data, stock):
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
stock_data_specific = stock_data[stock_data.Date <= '2021--06-14']
revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']
fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=True), y=stock_data_specific.Close.astype("float"), name="Share Price"), row=1, col=1)
fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date, infer_datetime_format=True), y=revenue_data_specific.Revenue.astype("float"), name="Revenue"), row=2, col=1)
fig.update_xaxes(title_text="Date", row=1, col=1)
fig.update_xaxes(title_text="Date", row=2, col=1)
fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
fig.update_layout(showlegend=False,
height=900,
title=stock,
xaxis_rangeslider_visible=True)
fig.show()
Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is Tesla and its ticker symbol is TSLA.
tesla = yf.Ticker("TSLA")
Using the ticker object and the function history extract stock information and save it in a dataframe named tesla_data. Set the period parameter to max so we get information for the maximum amount of time.
tesla_data = tesla.history(period="max")
Reset the index using the reset_index(inplace=True) function on the tesla_data DataFrame and display the first five rows of the tesla_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 1 to the results below.
tesla_data.reset_index(inplace=True)
tesla_data.head()
| Date | Open | High | Low | Close | Volume | Dividends | Stock Splits | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2010-06-29 | 1.266667 | 1.666667 | 1.169333 | 1.592667 | 281494500 | 0 | 0.0 |
| 1 | 2010-06-30 | 1.719333 | 2.028000 | 1.553333 | 1.588667 | 257806500 | 0 | 0.0 |
| 2 | 2010-07-01 | 1.666667 | 1.728000 | 1.351333 | 1.464000 | 123282000 | 0 | 0.0 |
| 3 | 2010-07-02 | 1.533333 | 1.540000 | 1.247333 | 1.280000 | 77097000 | 0 | 0.0 |
| 4 | 2010-07-06 | 1.333333 | 1.333333 | 1.055333 | 1.074000 | 103003500 | 0 | 0.0 |
Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm Save the text of the response as a variable named html_data.
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm"
html_data = requests.get(url).text
Parse the html data using beautiful_soup.
soup = BeautifulSoup(html_data, "html5lib")
Using BeautifulSoup or the read_html function extract the table with Tesla Revenue and store it into a dataframe named tesla_revenue. The dataframe should have columns Date and Revenue.
tables=soup.find_all("table")
for index,table in enumerate(tables):
if("Tesla Quarterly Revenue" in str(table)):
table_index=index
tesla_revenue=pd.DataFrame(columns=["Date","Revenue"])
for row in soup.find_all("tbody")[1].find_all("tr"):
col=row.find_all("td")
if(col!=[]):
date=col[0].text
revenue=col[1].text.strip().replace("$","").replace(",","")
tesla_reve = pd.DataFrame({"Date": date, "Revenue": revenue}, index=[1,2,3])
tesla_revenue=pd.concat([tesla_revenue, tesla_reve])
tesla_revenue.head()
| Date | Revenue | |
|---|---|---|
| 1 | 2022-09-30 | 21454 |
| 2 | 2022-09-30 | 21454 |
| 3 | 2022-09-30 | 21454 |
| 1 | 2022-06-30 | 16934 |
| 2 | 2022-06-30 | 16934 |
Execute the following line to remove the comma and dollar sign from the Revenue column.
tesla_revenue["Revenue"] = tesla_revenue['Revenue'].str.replace(',|\$',"")
Execute the following lines to remove an null or empty strings in the Revenue column.
tesla_revenue.dropna(inplace=True)
tesla_revenue = tesla_revenue[tesla_revenue['Revenue'] != ""]
Display the last 5 row of the tesla_revenue dataframe using the tail function. Take a screenshot of the results.
tesla_revenue.tail()
| Date | Revenue | |
|---|---|---|
| 2 | 2009-09-30 | 46 |
| 3 | 2009-09-30 | 46 |
| 1 | 2009-06-30 | 27 |
| 2 | 2009-06-30 | 27 |
| 3 | 2009-06-30 | 27 |
Using the Ticker function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is GameStop and its ticker symbol is GME.
gamestop = yf.Ticker("GME")
Using the ticker object and the function history extract stock information and save it in a dataframe named gme_data. Set the period parameter to max so we get information for the maximum amount of time.
gme_data=gamestop.history(period="max")
Reset the index using the reset_index(inplace=True) function on the gme_data DataFrame and display the first five rows of the gme_data dataframe using the head function. Take a screenshot of the results and code from the beginning of Question 3 to the results below.
gme_data.reset_index(inplace=True)
gme_data.head()
| Date | Open | High | Low | Close | Volume | Dividends | Stock Splits | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2002-02-13 | 1.620129 | 1.693350 | 1.603296 | 1.691667 | 76216000 | 0.0 | 0.0 |
| 1 | 2002-02-14 | 1.712707 | 1.716073 | 1.670626 | 1.683250 | 11021600 | 0.0 | 0.0 |
| 2 | 2002-02-15 | 1.683250 | 1.687458 | 1.658001 | 1.674834 | 8389600 | 0.0 | 0.0 |
| 3 | 2002-02-19 | 1.666418 | 1.666418 | 1.578047 | 1.607504 | 7410400 | 0.0 | 0.0 |
| 4 | 2002-02-20 | 1.615921 | 1.662210 | 1.603296 | 1.662210 | 6892800 | 0.0 | 0.0 |
Use the requests library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html. Save the text of the response as a variable named html_data.
gme_url="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html"
gme_html_data=requests.get(gme_url).text
Parse the html data using beautiful_soup.
gme_soup = BeautifulSoup(gme_html_data,"html5lib")
Using BeautifulSoup or the read_html function extract the table with GameStop Revenue and store it into a dataframe named gme_revenue. The dataframe should have columns Date and Revenue. Make sure the comma and dollar sign is removed from the Revenue column using a method similar to what you did in Question 2.
tables=gme_soup.find_all("table")
for index,table in enumerate(tables):
if("Gamestop Quarterly Revenue" in str(table)):
table_index=index
gme_revenue=pd.DataFrame(columns=["Date","Revenue"])
for row in gme_soup.find_all("tbody")[1].find_all("tr"):
col=row.find_all("td")
if(col!=[]):
date=col[0].text
revenue=col[1].text.strip().replace("$","").replace(",","")
gme_reve = pd.DataFrame({"Date": date, "Revenue": revenue}, index=[1,2,3])
gme_revenue=pd.concat([gme_revenue, gme_reve])
tesla_revenue.head()
| Date | Revenue | |
|---|---|---|
| 1 | 2022-09-30 | 21454 |
| 2 | 2022-09-30 | 21454 |
| 3 | 2022-09-30 | 21454 |
| 1 | 2022-06-30 | 16934 |
| 2 | 2022-06-30 | 16934 |
Display the last five rows of the gme_revenue dataframe using the tail function. Take a screenshot of the results.
gme_revenue.dropna(inplace=True)
gme_revenue.tail()
| Date | Revenue | |
|---|---|---|
| 2 | 2005-04-30 | 475 |
| 3 | 2005-04-30 | 475 |
| 1 | 2005-01-31 | 709 |
| 2 | 2005-01-31 | 709 |
| 3 | 2005-01-31 | 709 |
Use the make_graph function to graph the Tesla Stock Data, also provide a title for the graph. The structure to call the make_graph function is make_graph(tesla_data, tesla_revenue, 'Tesla'). Note the graph will only show data upto June 2021.
make_graph(tesla_data, tesla_revenue, 'Tesla Stock Data')
/tmp/ipykernel_68907/2225176002.py:5: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument. /tmp/ipykernel_68907/2225176002.py:6: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.
Use the make_graph function to graph the GameStop Stock Data, also provide a title for the graph. The structure to call the make_graph function is make_graph(gme_data, gme_revenue, 'GameStop'). Note the graph will only show data upto June 2021.
make_graph(gme_data, gme_revenue, 'Gamestop Stock Data Graph')
/tmp/ipykernel_68907/2225176002.py:5: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument. /tmp/ipykernel_68907/2225176002.py:6: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.
Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.
Azim Hirjani
| Date (YYYY-MM-DD) | Version | Changed By | Change Description |
|---|---|---|---|
| 2022-02-28 | 1.2 | Lakshmi Holla | Changed the URL of GameStop |
| 2020-11-10 | 1.1 | Malika Singla | Deleted the Optional part |
| 2020-08-27 | 1.0 | Malika Singla | Added lab to GitLab |